package com.consumer.service.impl;

import com.consumer.model.Result;
import com.consumer.model.table.SysMessage;
import com.consumer.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.consumer.service.MessageService;
import com.consumer.repository.MessageRepository;

import java.util.Optional;

/**
 * @author Liunh
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    private final MessageRepository repository;

    public MessageServiceImpl(MessageRepository repository) {
        this.repository = repository;
    }


    @Override
    public Result<SysMessage> add(SysMessage req) throws Exception {
        final Result<SysMessage> result = new Result<SysMessage>().invokeSuccess();
        try {
            if (req != null && req.getId() == null) {
                if (req.getMsgType() == null) {
                    req.setMsgType(0);
                }
                if (req.getMsgType() == 0) {
                    req.setStatus(1);
                }
                req.setCreateTime(DateUtil.getCurrentDate());
                final Optional<SysMessage> optional = this.save(req);
                result.setData(optional.orElse(null));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("保存消息数据异常！信息来源[" + req.getSource() + "]、消息描述[" + req.getDescr() + "]。");
            log.error(">>>>>> 保存消息数据异常！信息来源[" + req.getSource() + "]、消息描述[" + req.getDescr() + "]。", e);
        }
        return result;
    }

    private Optional<SysMessage> save(SysMessage req) throws Exception {
        if (req != null && req.getId() == null) {
            if (req.getMsgType() == null) {
                req.setMsgType(0);
            }
            if (req.getMsgType() == 0) {
                req.setStatus(1);
                if (req.getSendTime() == null) {
                    req.setSendTime(DateUtil.getCurrentDate());
                }
            }
            req.setCreateTime(DateUtil.getCurrentDate());
            final SysMessage save = repository.save(req);
            return Optional.of(save);
        }
        return Optional.empty();
    }

}
